package com.example.baserapitaxi;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

import utils.PreferencesHelper;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;

public abstract class BaseMainActivity extends Activity
{
	public static final String EXTRA_MESSAGE = "message";
    public static final String PROPERTY_REG_ID = "registration_id";
    private static final String PROPERTY_APP_VERSION = "appVersion";
    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    
    private String SENDER_ID = "12208215485";
    
    private String regid;

    GoogleCloudMessaging gcm;
    AtomicInteger msgId = new AtomicInteger();
    private Context context;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_base_main);
		
		context = getApplicationContext();
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		
		if (checkPlayServices())
		{
			gcm = GoogleCloudMessaging.getInstance(this);
			regid = getRegistrationId(context);
			
			if (regid.isEmpty())
				registerInBackground();
			else
				continuar();
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings)
		{
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	/**
	 * Verifica que el dispositivo soporte Google Play Services.
	 * @return true si lo soporta, false si no.
	 */
	private boolean checkPlayServices()
	{
		int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
		
		if (resultCode != ConnectionResult.SUCCESS)
		{
			if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
			{
				GooglePlayServicesUtil.getErrorDialog(resultCode, this,
						PLAY_SERVICES_RESOLUTION_REQUEST).show();
			} 
			else
			{
				Log.i("LOG", "This device is not supported.");
				finish();
			}
			return false;
		}
		return true;
	}
	
	private String getRegistrationId(Context context) {
        final SharedPreferences prefs = getGCMPreferences(context);
        String registrationId = prefs.getString(PROPERTY_REG_ID, "");
        if (registrationId.isEmpty()) {
            Log.i("LOG", "Registration not found.");
            return "";
        }
        // Check if app was updated; if so, it must clear the registration ID
        // since the existing regID is not guaranteed to work with the new
        // app version.
        int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
        int currentVersion = getAppVersion(context);
        if (registeredVersion != currentVersion) {
            Log.i("LOG", "App version changed.");
            return "";
        }
        return registrationId;
    }
	
	/**
     * @return Application's {@code SharedPreferences}.
     */
    private SharedPreferences getGCMPreferences(Context context) {
        // This sample app persists the registration ID in shared preferences, but
        // how you store the regID in your app is up to you.
        return getSharedPreferences(BaseMainActivity.class.getSimpleName(),
                Context.MODE_PRIVATE);
    }
    
    /**
     * @return Application's version code from the {@code PackageManager}.
     */
    private static int getAppVersion(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (NameNotFoundException e) {
            // should never happen
            throw new RuntimeException("Could not get package name: " + e);
        }
    }

    private void registerInBackground ()
    {
    	new AsyncTask<String,String,String>()
        {
            @Override
            protected String doInBackground(String... params) 
            {
            	boolean intentar = true;
            	
            	while (intentar)
            	{
	                try 
	                {
	                    if (gcm == null)
	                        gcm = GoogleCloudMessaging.getInstance(context);
	                    
	                	regid = gcm.register(SENDER_ID);
	                    
	                    storeRegistrationId(context, regid);
	                    intentar = false;
	                } 
	                catch (IOException ex) 
	                {
	                	Log.i("LOG", "Excepcion registrando GCM: " + ex.getMessage());
	                }
            	}

            	return "";
            }

            @Override
            protected void onPostExecute(String msg) 
            {
            	//TextView tv = (TextView) findViewById(R.id.campo);
            	//tv.setText(msg);
            	sendRegistrationIdToBackend(regid);
            }
        }.execute(null, null, null);
    }
    
    private void storeRegistrationId(Context context, String regId) 
    {
        final SharedPreferences prefs = getGCMPreferences(context);
        int appVersion = getAppVersion(context);
        Log.i("LOG", "Saving regId on app version " + appVersion);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(PROPERTY_REG_ID, regId);
        editor.putInt(PROPERTY_APP_VERSION, appVersion);
        editor.commit();
    }
    
    /**
     * Envia el cogido GCM obtenido al servidor.
     * @param reg el codigo GCM.
     */
    private void sendRegistrationIdToBackend(String reg)
    {
    	if (reg != null && !reg.equals(""))
		{
			PreferencesHelper helper = new PreferencesHelper(getApplicationContext());
			helper.editKey(PreferencesHelper.GCM, reg);
			
			continuar();
		}
    }
    
    /**
     * Una vez que el GCM fue registrado, se continua con la aplicacion.
     */
    protected abstract void continuar();
}
